package com.unlcn.ils.wms.backend.service.bigscreen.impl;

import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.unlcn.ils.wms.backend.bo.biBO.BiTransModeBO;
import com.unlcn.ils.wms.backend.dto.bigscreenDTO.TransModelDTO;
import com.unlcn.ils.wms.backend.enums.TmsUrlEnum;
import com.unlcn.ils.wms.backend.enums.TmsUrlTypeEnum;
import com.unlcn.ils.wms.backend.enums.TransModeEnum;
import com.unlcn.ils.wms.backend.service.bigscreen.TransModelService;
import com.unlcn.ils.wms.backend.util.TimeUtil;
import com.unlcn.ils.wms.base.mapper.bigscreen.BiTransModelMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.BiTransModelExtMapper;
import com.unlcn.ils.wms.base.mapper.sys.TmsCallHistoryMapper;
import com.unlcn.ils.wms.base.model.bigscreen.BiTransModel;
import com.unlcn.ils.wms.base.model.sys.TmsCallHistory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 发运模式推移图service
 */
@Service
public class TransModelServiceImpl implements TransModelService{

    @Autowired
    private BiTransModelExtMapper biTransModelExtMapper;

    @Autowired
    private BiTransModelMapper biTransModelMapper;

    @Value("${tms.pickup.host.url}")
    private String propertyUrl;

    @Value("${tms.pickup.host.timeout}")
    private String propertyTime;

    @Value("${tms.encode.key}")
    private String propertyKey;

    @Autowired
    private TmsCallHistoryMapper tmsCallHistoryMapper;

    private Logger LOGGER = LoggerFactory.getLogger(TransModelServiceImpl.class);

    @Override
    public List<TransModelDTO> transModelChartCount() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        List<BiTransModel> biTransModelList = biTransModelExtMapper.transModelChartCount();

        TransModelDTO transModelDTO1 = new TransModelDTO();
        TransModelDTO transModelDTO2 = new TransModelDTO();
        TransModelDTO transModelDTO3 = new TransModelDTO();
        TransModelDTO transModelDTO4 = new TransModelDTO();

        transModelDTO1.setName("陆运");
        transModelDTO2.setName("铁运");
        transModelDTO3.setName("水运");
        //bugfix 2017-12-18 增加人送模式数据
        transModelDTO4.setName("人送");

        Integer[] count1 = new Integer[5];
        Integer[] count2 = new Integer[5];
        Integer[] count3 = new Integer[5];
        Integer[] count4 = new Integer[5];

        String[] dates = TimeUtil.getBeforeDates1(5);

        for (int i=0; dates.length>i; i++) {
            String date = dates[i];
            for (int num=0; biTransModelList.size()>num; num++) {
                BiTransModel biTransModel = biTransModelList.get(num);

                if (!format.format(biTransModel.getStatisticsTime()).contains(date))
                    continue;

                // 陆运
                if (TransModeEnum.ROAD.getValue().equals(biTransModel.getTransModel())) {
                    count1[i] = biTransModel.getTransModelCount();
                }
                System.out.println("test:"+biTransModel.getTransModel());
                // 铁运
                if (TransModeEnum.RALT.getValue().equals(biTransModel.getTransModel())) {
                    count2[i] = biTransModel.getTransModelCount();
                }
                // 水运
                if (TransModeEnum.WATER.getValue().equals(biTransModel.getTransModel())) {
                    count3[i] = biTransModel.getTransModelCount();
                }
                // 人送
                if (TransModeEnum.PERSON.getValue().equals(biTransModel.getTransModel())) {
                    count4[i] = biTransModel.getTransModelCount();
                }
            }
        }
        for (Integer num=0; count1.length>num; num++) {
            Integer count = count1[num];
            if (count == null)
                count1[num] = 0;
        }
        for (Integer num=0; count2.length>num; num++) {
            Integer count = count2[num];
            if (count == null)
                count2[num] = 0;
        }
        for (Integer num=0; count3.length>num; num++) {
            Integer count = count3[num];
            if (count == null)
                count3[num] = 0;
        }
        for (Integer num=0; count4.length>num; num++) {
            Integer count = count4[num];
            if (count == null)
                count4[num] = 0;
        }

        transModelDTO1.setData(count1);
        transModelDTO2.setData(count2);
        transModelDTO3.setData(count3);
        transModelDTO4.setData(count4);

        transModelDTO1.setDate(TimeUtil.getBeforeDates2(5));
        transModelDTO2.setDate(TimeUtil.getBeforeDates2(5));
        transModelDTO3.setDate(TimeUtil.getBeforeDates2(5));
        transModelDTO4.setDate(TimeUtil.getBeforeDates2(5));

        List<TransModelDTO> shipmentDataDTOList = new ArrayList<TransModelDTO>();
        shipmentDataDTOList.add(transModelDTO1);
        shipmentDataDTOList.add(transModelDTO2);
        shipmentDataDTOList.add(transModelDTO3);
        shipmentDataDTOList.add(transModelDTO4);

        return shipmentDataDTOList;
    }

    @Override
    public void addTransMode() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        String dateStr = format.format(calendar.getTime());

        String strUrl=propertyUrl + TmsUrlEnum.BI_TRANSMODE.getText();
        Integer time = Integer.parseInt(propertyTime);
        String encode_key = propertyKey;
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("encode-key", encode_key);

        map.put("date", dateStr);

        String result = null;

        TmsCallHistory tmsCallHistory=new TmsCallHistory();

        try {

            tmsCallHistory.setTmsUrl(strUrl);
            tmsCallHistory.setPullOrPush(0);
            tmsCallHistory.setCallStartTime(new Date());
            tmsCallHistory.setTmsUrlType(TmsUrlTypeEnum.BI_TRANSMODE.getValue());
            tmsCallHistory.setParameters(dateStr);
            result = HttpRequestUtil.sendHttpPost(strUrl, headerMap, map, time);

        } catch (Exception e) {
            LOGGER.error("TransModelServiceImpl.addTransMode error : ", e);
            throw new BusinessException("访问tms接口失败");
        }

        try{
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                String msg = jsonObject.getString("message");
                String records = jsonObject.getString("records");
                Boolean success = jsonObject.getBoolean("success");

                tmsCallHistory.setCallEndTime(new Date());
                tmsCallHistory.setMessage(msg);
                tmsCallHistory.setResultContent(result);

                if (!success) {
                    LOGGER.error("TransModelServiceImpl callTms error msg: {}", msg);
                    tmsCallHistory.setResultCount(0);
                    tmsCallHistory.setSuccess(success);
                    tmsCallHistoryMapper.insertSelective(tmsCallHistory);
                }

                List<BiTransModeBO> tmsBOList = JSONArray.parseArray(records,BiTransModeBO.class);
                tmsCallHistory.setResultCount(tmsBOList.size());
                tmsCallHistory.setSuccess(success);
                tmsCallHistoryMapper.insertSelective(tmsCallHistory);

                SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmSS");
                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTime(new Date());
                String dateStr2 = format2.format(calendar2.getTime());

                tmsBOList.forEach((BiTransModeBO v) -> {
                    for(int i=0;i<4;i++){
                        //新增
                        BiTransModel biTransModel = new BiTransModel();

                        //水运
                        if(i==0){
                            biTransModel.setTransModel(TransModeEnum.WATER.getValue());
                            biTransModel.setTransModelCount(Integer.parseInt(Strings.isNullOrEmpty(v.getDock_qty())?"0":v.getDock_qty()));
                        }

                        //铁运
                        if(i==1){
                            biTransModel.setTransModel(TransModeEnum.RALT.getValue());
                            biTransModel.setTransModelCount(Integer.parseInt(Strings.isNullOrEmpty(v.getRail_qty())?"0":v.getRail_qty()));
                        }

                        //陆运
                        if(i==2){
                            biTransModel.setTransModel(TransModeEnum.ROAD.getValue());
                            biTransModel.setTransModelCount(Integer.parseInt(Strings.isNullOrEmpty(v.getTruck_qty())?"0":v.getTruck_qty()));
                        }

                        //人送
                        if(i==3){
                            biTransModel.setTransModel(TransModeEnum.PERSON.getValue());
                            biTransModel.setTransModelCount(Integer.parseInt(Strings.isNullOrEmpty(v.getRoad_qty())?"0":v.getRoad_qty()));
                        }

                        biTransModel.setVersion(dateStr2);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

                        try {
                            biTransModel.setStatisticsTime(sdf.parse(v.getRpt_date()));
                        } catch (ParseException e) {
                            LOGGER.error("TransModelServiceImpl.addTransMode error : ", e);
                            throw new BusinessException("日期转换异常!");
                        }

                        biTransModelMapper.insertSelective(biTransModel);
                    }
                });
            }

        }
        catch (Exception e) {
            LOGGER.error("TransModelServiceImpl.addTransMode error : ", e);
            throw new BusinessException("保存失败");
        }
    }
}
